﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Collections.Specialized;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Net;
using System.Text;
using iTextSharp.text.html.simpleparser;
using System.Threading;

public partial class _Default : System.Web.UI.Page
{
    List<_Invoice> my_users_doc_list = new List<_Invoice>();
    List<_Invoice> my_doc_list = new List<_Invoice>();

    List<_User> User_list = new List<_User>();

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {      
        if (Request.IsAuthenticated == false)
        {
            Response.Redirect("login.aspx");
        }

        if (Request.IsAuthenticated)
        {
            string n = "";
            SqlCommand sCmd = new SqlCommand("SELECT name FROM USERS WHERE id=@id", conn);
            sCmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = User.Identity.Name;
            conn.Open();
            SqlDataReader dr = sCmd.ExecuteReader();
            while (dr.Read())
            {
                string name = Convert.ToString(dr[0].ToString());
                n = name;
            }
            dr.Close();
            conn.Close();

            WelcomeBackMessage.Text = "Welcome back, " + n + "!";

            AuthenticatedHeaderPanel.Visible = true;
            AuthenticatedMessagePanel.Visible = true;
            AuthenticatedMenuPanel.Visible = true;

            if (!IsPostBack)
            {
                SetData(tb_search.Text, status.Text);
            }
        }
        else
        {
            AuthenticatedHeaderPanel.Visible = false;
            AuthenticatedMessagePanel.Visible = false;
            AuthenticatedMenuPanel.Visible = false;
        }
    }

    private void SetData(string document_number_search, string status)
    {
        //Atlasa ielogotā lietotaja, lietotāju dokumentus Default.aspx
        my_users_doc_list = _Invoice.SelectInvoices(User.Identity.Name);
        if (my_users_doc_list.Count == 0)
        {
            message.Visible = true;            
        }
        else
        {
            message.Visible = false;            
            My_users_documents_list.DataSource = my_users_doc_list;
            My_users_documents_list.DataBind();
        }

        my_doc_list = _Invoice.Select_My_Invoices(document_number_search, status, User.Identity.Name);
        if (my_doc_list.Count == 0)
        {
            if (status == "Deleted" && my_doc_list.Count == 0)
            {
                message2.Visible = true;
                message2Text.InnerText = "You have no deleted documents!";
                search.Visible = true;
                bt_delete_my_selected_invoices.Visible = false;
                My_documents_list.DataSource = my_doc_list;
                My_documents_list.DataBind();
                
            }
            else if (status == "Active" && my_doc_list.Count == 0)
            {
                message2.Visible = true;
                message2Text.InnerText = "You have no active documents!";
                search.Visible = true;
                bt_delete_my_selected_invoices.Visible = false;
                My_documents_list.DataSource = my_doc_list;
                My_documents_list.DataBind();
            }
            else
            {
                message2.Visible = true;
                search.Visible = false;
                bt_delete_my_selected_invoices.Visible = false;
            }
        }
        else
        {
            message2.Visible = false;
            search.Visible = true;
            My_documents_list.DataSource = my_doc_list;
            My_documents_list.DataBind();
            bt_delete_my_selected_invoices.Visible = true;

             //Atrod dokumentus kuriem statuss ir dzēsts un neļaujam šārēt, rediģēt, dzēst
            List<int> documents_id = new List<int>();
            SqlCommand SelCmd = new SqlCommand("SELECT id FROM document WHERE id_issued_by_user=@issued_by_user_id AND statuss=@status", conn);
            SelCmd.Parameters.Add(new SqlParameter("issued_by_user_id", SqlDbType.Int)).Value = User.Identity.Name;
            SelCmd.Parameters.Add(new SqlParameter("status", SqlDbType.VarChar)).Value = "Deleted";
            conn.Open();
            SqlDataReader dr = SelCmd.ExecuteReader();
            while (dr.Read())
            {
                documents_id.Add(Convert.ToInt32(dr["id"].ToString()));
            }
            dr.Close();
            conn.Close();

            foreach (ListViewItem item in My_documents_list.Items)
            {
                Label doc_id = (Label)item.FindControl("my_doc_IDLabel");
                foreach (int id in documents_id)
                {
                    if (doc_id.Text == Convert.ToString(id))
                    {
                        ImageButton edit = (ImageButton)item.FindControl("lnkEdit");
                        ImageButton share = (ImageButton)item.FindControl("lnkShare");
                        ImageButton delete = (ImageButton)item.FindControl("lnkDelete");
                        CheckBox chx = (CheckBox)item.FindControl("check_delete_doc");

                        edit.Enabled = false;
                        share.Enabled = false;
                        delete.Enabled = false;
                        chx.Enabled = false;
                    }
                }
            }
        }
    }

    // Slēpjam nevajadzīgās kolonnas
    protected void My_users_documents_list_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        e.Item.FindControl("idL").Visible = false;
        e.Item.FindControl("docID").Visible = false;
    }
    protected void My_users_documents_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "doc_num_users")
        {
            my_users_doc_list = _Invoice.SelectInvoices(User.Identity.Name);
            my_users_doc_list.Sort((x, y) => String.CompareOrdinal(x.document_number, y.document_number));
            var newList1 = my_users_doc_list.OrderBy(x => x.document_number).ToList();
            My_users_documents_list.DataSource = newList1;
            My_users_documents_list.DataBind();
        }
        if (e.CommandName == "doc_num_users_desc")
        {
            my_users_doc_list = _Invoice.SelectInvoices(User.Identity.Name);
            my_users_doc_list.Sort((x, y) => String.CompareOrdinal(x.document_number, y.document_number));
            var newList1 = my_users_doc_list.OrderByDescending(x => x.document_number).ToList();
            My_users_documents_list.DataSource = newList1;
            My_users_documents_list.DataBind();
        }

        if (e.CommandName == "doc_date_user")
        {
            my_users_doc_list = _Invoice.SelectInvoices(User.Identity.Name);
            my_users_doc_list.Sort((x, y) => String.CompareOrdinal(x.document_date.ToString(), y.document_date.ToString()));
            var newList1 = my_users_doc_list.OrderBy(x => x.document_date).ToList();
            My_users_documents_list.DataSource = newList1;
            My_users_documents_list.DataBind();
        }
        if (e.CommandName == "doc_date_user_desc")
        {
            my_users_doc_list = _Invoice.SelectInvoices(User.Identity.Name);
            my_users_doc_list.Sort((x, y) => String.CompareOrdinal(x.document_date.ToString(), y.document_date.ToString()));
            var newList1 = my_users_doc_list.OrderByDescending(x => x.document_date).ToList();
            My_users_documents_list.DataSource = newList1;
            My_users_documents_list.DataBind();
        }

        if (e.CommandName == "Invoice")
        {
            var id_document = e.Item.FindControl("doc_IDLabel") as Label;
            string user_doc = "user_doc";
            //padod sesijai mana dokumenta ID
            Session["Doc_ID"] = id_document.Text;
            //padod sesijai mana lietotāja dokumenta ID
            Session["user_doc"] = user_doc;
            Response.Redirect("ViewInvoice.aspx");
        }
    }

    string docnumb = "";
    int docid = 0;
    protected void My_documents_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "doc_num")
        {
            my_doc_list = _Invoice.Select_My_Invoices(tb_search.Text, "", User.Identity.Name);
            my_doc_list.Sort((x, y) => String.CompareOrdinal(x.document_number, y.document_number));
            var newList = my_doc_list.OrderBy(x => x.document_number).ToList();
            My_documents_list.DataSource = newList;
            My_documents_list.DataBind();
        }
        if (e.CommandName == "doc_num_desc")
        {
            my_doc_list = _Invoice.Select_My_Invoices(tb_search.Text, "", User.Identity.Name);
            my_doc_list.Sort((x, y) => String.CompareOrdinal(x.document_number, y.document_number));
            var newList = my_doc_list.OrderByDescending(x => x.document_number).ToList();
            My_documents_list.DataSource = newList;
            My_documents_list.DataBind();
        }

        if (e.CommandName == "doc_date")
        {
            my_doc_list = _Invoice.Select_My_Invoices(tb_search.Text, "", User.Identity.Name);
            my_doc_list.Sort((x, y) => String.CompareOrdinal(x.document_date.ToString(), y.document_date.ToString()));
            var newList = my_doc_list.OrderBy(x => x.document_date).ToList();
            My_documents_list.DataSource = newList;
            My_documents_list.DataBind();
        }
        if (e.CommandName == "doc_date_desc")
        {
            my_doc_list = _Invoice.Select_My_Invoices(tb_search.Text, "", User.Identity.Name);
            my_doc_list.Sort((x, y) => String.CompareOrdinal(x.document_date.ToString(), y.document_date.ToString()));
            var newList = my_doc_list.OrderByDescending(x => x.document_date).ToList();
            My_documents_list.DataSource = newList;
            My_documents_list.DataBind();
        }

        if (e.CommandName == "Invoice")
        {
            var id_document = e.Item.FindControl("my_doc_IDLabel") as Label;
            docnumb = id_document.Text;
            string my_doc = "My_doc";
            //padod sesijai mana dokumenta ID
            Session["Doc_ID"] = id_document.Text;
            //padod sesijai mana lietotāja dokumenta ID
            Session["user_doc"] = my_doc;
            Response.Redirect("ViewInvoice.aspx");
        }

        if (e.CommandName == "Edit")
        {
            //Iegūstam id_issued_user un document_id un padodam _User un _Invoive klasei lai atlasītu datus priekš "Add document" POPUP
            var id_user = e.Item.FindControl("my_id_issued_userLabel") as Label;
            var id_document = e.Item.FindControl("my_doc_IDLabel") as Label;
            Session["User_ID"] = id_user.Text;
            Session["Doc_ID"] = id_document.Text;
            EditDocument(id_user.Text, id_document.Text);
        }

        if (e.CommandName == "Share")
        {
            var id_document = e.Item.FindControl("my_doc_IDLabel") as Label;
            Session["Doc_ID"] = id_document.Text;
            share_document_ID.Text = id_document.Text;

            var id_issued_user = e.Item.FindControl("my_id_issued_userLabel") as Label;
            Session["userID"] = id_issued_user.Text;
            share_document_user_ID.Text = id_issued_user.Text;

            var doc_num = e.Item.FindControl("my_document_numLabel") as Label;
            Session["Doc_Num"] = doc_num.Text;
            share_document_number.Text = doc_num.Text;
            SetDataPopup();
            Modal_PopupShare.Show();
        }

        if (e.CommandName == "Delete")
        {
            var id_document = e.Item.FindControl("my_doc_IDLabel") as Label;
            IDdoc.Text = id_document.Text;

            List<string> doc_number = new List<string>();
            var doc_num = e.Item.FindControl("my_document_numLabel") as Label;
            SqlCommand selCmd = new SqlCommand("SELECT document_number FROM  document WHERE document_number=@document_number", conn);
            selCmd.Parameters.Add(new SqlParameter("@document_number", SqlDbType.NVarChar)).Value = doc_num.Text;
            conn.Open();
            SqlDataReader dr = selCmd.ExecuteReader();
            while (dr.Read())
            {
                doc_number.Add(dr["document_number"].ToString());
            }

            if (doc_number.Count > 1)
            {
                delete_message_text.InnerText = "This document is shared with other users!";
                bt_delete_to_all.Visible = true;
                delete_me.InnerText = "Only Me";
            }
            else if (doc_number.Count == 1)
            {
                delete_message_text.InnerText = "Are you sure?";
                bt_delete_to_all.Visible = false;
                delete_me.InnerText = "Delete";
            }
            conn.Close();
            dr.Close();
            Modal_Popup_Delete.Show();
        }

        //if (e.CommandName == "PDF")
        //{
        //    var invoice = e.Item.FindControl("my_document_numLabel") as Label;
        //    string n = string.Format("{0:dd_MM_yyyy}", DateTime.Now);
        //    Response.ContentType = "application/pdf";
        //    Response.AddHeader("content-disposition", "attachment;filename=" + invoice.Text + "_" + n + ".pdf");
        //    Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //    StringWriter sw = new StringWriter();
        //    HtmlTextWriter hw = new HtmlTextWriter(sw);

        //    var document = new Document(PageSize.A4, 50, 50, 25, 25);
        //    var stream = new MemoryStream();

        //    // Izveido PDF turpat mapē
        //    //var output = new FileStream(Server.MapPath("MyFirstPDF.pdf"), FileMode.Create);
        //    //var writer = PdfWriter.GetInstance(document, output);

        //    StringReader sr = new StringReader(sw.ToString());
        //    HTMLWorker htmlparser = new HTMLWorker(document);
        //    PdfWriter.GetInstance(document, Response.OutputStream);
        //    // Atver dokumentu lai ierakstītu
        //    document.Open();
        //    var welcomeParagraph = new Paragraph("Hello, World!");
        //    document.Add(welcomeParagraph);
        //    document.Close();
        //    Response.Write(document);
        //    Response.End();

        //    // Izvada un atver uz ekrāna jaunā logā pdf...
        //    //string path = output.Name.ToString();
        //    //WebClient client = new WebClient();
        //    //Byte[] buffer = client.DownloadData(path);

        //    //if (buffer != null)
        //    //{
        //    //    Response.ContentType = "application/pdf";
        //    //    Response.AddHeader("content-length", buffer.Length.ToString());
        //    //    Response.BinaryWrite(buffer);
        //    //}
        //}
    }
    protected void My_document_list_Editing(object sender, ListViewEditEventArgs e)
    {

    }    
        
    private void SetDataPopup()
    {
        User_list = _User.SelUser(User.Identity.Name);

        if (User_list.Count == 0)
        {
            content.Visible = true;
            message3.Visible = true;
            bt_share.Visible = false;
        }
        else
        {
            content.Visible = false;
            message3.Visible = false;
            My_users_share_list.DataSource = User_list;
            My_users_share_list.DataBind();
            bt_share.Visible = true;

            List<int> users = new List<int>();
            SqlCommand SelCmd = new SqlCommand("SELECT id_issued_by_user FROM document WHERE document_number=@doc_num", conn);
            SelCmd.Parameters.Add(new SqlParameter("doc_num", SqlDbType.NVarChar)).Value = share_document_number.Text.ToString();
            conn.Open();
            SqlDataReader dr = SelCmd.ExecuteReader();
            while (dr.Read())
            {
                users.Add(Convert.ToInt32(dr["id_issued_by_user"].ToString()));
                if (users.Contains(Convert.ToInt32(User.Identity.Name)))
                {
                    users.Remove(Convert.ToInt32(User.Identity.Name));
                }
            }
            dr.Close();
            conn.Close();

            foreach (ListViewItem item in My_users_share_list.Items)
            {
                CheckBox cb = (CheckBox)item.FindControl("check_share");
                foreach (int user in users)
                {
                    Label id_user = (Label)item.FindControl("idLabel");
                    string user_id = id_user.Text;
                    if (user_id == user.ToString())
                    {
                        cb.Checked = true;
                    }
                }
            }
            Response.Clear();
        }
    }

    // Slēpjam nevajadzīgās kolonnas
    protected void My_users_share_list_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        e.Item.FindControl("idL").Visible = false;
    }

    protected void bt_share_Click(object sender, EventArgs e)
    {
        string doc_num = " ";
        string doc_date = " ";
        string doc_pay_date = " ";
        string comp_by = " ";
        string comp_to = " ";
        string doc_type = " ";
        string pay_type = " ";
        string del_place = " ";
        string address_comp_by = " ";
        string address_client_to = " ";
        string bank_company_by = " ";
        string bank_client_to = " ";
        string account_company_by = " ";
        string account_client_to = " ";
        string statuss = " ";

        conn.Open();
        SqlCommand selCmd = new SqlCommand("SELECT * FROM document WHERE id=@document_id", conn);
        selCmd.Parameters.Add(new SqlParameter("@document_id", SqlDbType.Int)).Value = Convert.ToInt32(share_document_ID.Text);
        SqlDataReader dr = selCmd.ExecuteReader();
        while (dr.Read())
        {
            doc_num = dr[1].ToString();
            doc_date = dr[2].ToString();
            doc_pay_date = dr[3].ToString();
            comp_by = dr[5].ToString();
            comp_to = dr[6].ToString();
            doc_type = dr[8].ToString();
            pay_type = dr[9].ToString();
            del_place = dr[10].ToString();
            address_comp_by = dr[11].ToString();
            address_client_to = dr[12].ToString();
            bank_company_by = dr[13].ToString();
            bank_client_to = dr[14].ToString();
            account_company_by = dr[15].ToString();
            account_client_to = dr[16].ToString();
            statuss = dr[17].ToString();
        }
        dr.Close();
        conn.Close();

        List<int> users = new List<int>();
        SqlCommand SelCmd = new SqlCommand("SELECT id_issued_by_user FROM document WHERE document_number=@doc_num", conn);
        SelCmd.Parameters.Add(new SqlParameter("doc_num", SqlDbType.NVarChar)).Value = share_document_number.Text;
        conn.Open();
        SqlDataReader dr2 = SelCmd.ExecuteReader();
        while (dr2.Read())
        {
            users.Add(Convert.ToInt32(dr2["id_issued_by_user"].ToString()));
            if (users.Contains(Convert.ToInt32(share_document_user_ID.Text)))
            {
                users.Remove(Convert.ToInt32(share_document_user_ID.Text));
            }
        }
        dr2.Close();
        conn.Close();

        List<int> user = new List<int>();
        List<int> user2 = new List<int>();
        foreach (ListViewItem item in My_users_share_list.Items)
        {
            CheckBox cb = (CheckBox)item.FindControl("check_share");
            if (cb.Checked)
            {
                Label id_user = (Label)item.FindControl("idLabel");
                int user_id = Convert.ToInt32(id_user.Text);
                user.Add(user_id);
                foreach (int us in users)
                {
                    if (user.Contains(us))
                    {
                        user.Remove(us);
                    }
                }
            }

            if (cb.Checked == false)
            {
                Label id_user = (Label)item.FindControl("idLabel");
                int user_id = Convert.ToInt32(id_user.Text);
                user2.Add(user_id);
            }
        }

        foreach (var i in user2)
        {
            SqlCommand DelCmd = new SqlCommand("DELETE FROM document WHERE document_number=@doc_num AND id_issued_by_user=@user_id", conn);
            DelCmd.Parameters.Add(new SqlParameter("doc_num", SqlDbType.NVarChar)).Value = share_document_number.Text;
            DelCmd.Parameters.Add(new SqlParameter("user_id", SqlDbType.Int)).Value = i;
            conn.Open();
            DelCmd.ExecuteNonQuery();
            conn.Close();
        }

        foreach (int id in user)
        {
            _Invoice.Insert(doc_num, doc_date, doc_pay_date, id.ToString(), comp_by, comp_to, doc_type, pay_type, del_place, address_comp_by, address_client_to, bank_company_by, bank_client_to, account_company_by, account_client_to, statuss);
        }
        Modal_PopupShare.Show();
        share_modal_message.Text = "Saved!";
        //UpdatePanel2.ChildrenAsTriggers = true;
        SetData(tb_search.Text, status.Text);
    }
    protected void bt_share_cancel_Click(object sender, EventArgs e)
    {
        Modal_PopupShare.Hide();
        SetData(tb_search.Text, status.Text);
    }

    // Slēpjam nevajadzīgās kolonnas un iekrāsojam rindas NESTRĀDĀ JO CSS FORMĒ LISTU
    protected void My_documents_list_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        e.Item.FindControl("my_idL").Visible = false;
        e.Item.FindControl("my_docID").Visible = false;
        e.Item.FindControl("my_doc_num").Visible = false;

        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataitem = (ListViewDataItem)e.Item;
            string policyid = (string)DataBinder.Eval(dataitem.DataItem, "status");
            if (policyid == "Deleted")
            {
                HtmlTableRow cell = (HtmlTableRow)e.Item.FindControl("_itemrow");
                cell.Style.Add("background-color", "Red");
            }
        }
    }

    List<string> selected_docNumb = new List<string>();
    List<string> issued_by_user = new List<string>();
    protected void bt_delete_my_selected_invoices_Click(object sender, EventArgs e)
    {
        Delete();
        if (selected_docNumb.Count == 0)
        {
            Page.ClientScript.RegisterStartupScript(typeof(Page), "myalert", "alert('Select documents to delete');", true);
        }
    }

    private void Delete()
    {
        foreach (ListViewItem item in My_documents_list.Items)
        {
            CheckBox cb = (CheckBox)item.FindControl("check_delete_doc");
            if (cb.Checked)
            {
                Label id_doc = (Label)item.FindControl("my_document_numLabel");
                string doc_id = id_doc.Text;
                selected_docNumb.Add(doc_id);

                foreach (string docNum in selected_docNumb)
                {
                    //selekto userus kuriem ir šārēts ieķeksētais dokuments izņemot pašu ielogoto useri
                    SqlCommand selCmd = new SqlCommand("SELECT id_issued_by_user FROM document WHERE document_number=@document_number AND id_issued_by_user<>@id_issued_by_user", conn);
                    selCmd.Parameters.Add(new SqlParameter("@document_number", SqlDbType.NVarChar)).Value = docNum;
                    selCmd.Parameters.Add(new SqlParameter("@id_issued_by_user", SqlDbType.Int)).Value = User.Identity.Name;
                    conn.Open();
                    SqlDataReader dr = selCmd.ExecuteReader();
                    while (dr.Read())
                    {
                        issued_by_user.Add(dr["id_issued_by_user"].ToString());
                    }
                    dr.Close();
                    conn.Close();
                    if (issued_by_user.Count > 0)
                    {
                        delete_message_text.InnerText = "Some of the selected documents are shared with other users!";
                        bt_delete_to_all.Visible = true;
                        delete_me.InnerText = "Only Me";
                        Modal_Popup_Delete.Show();
                    }
                    else
                    {
                        delete_message_text.InnerText = "Are you sure?";
                        bt_delete_to_all.Visible = false;
                        delete_me.InnerText = "Delete";
                        Modal_Popup_Delete.Show();
                    }
                }
            }
        }
    }

    protected void My_documents_list_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        //Label lbl = (My_documents_list.Items[e.ItemIndex].FindControl("my_doc_IDLabel")) as Label;
        //SqlCommand UpCmd = new SqlCommand("UPDATE DOCUMENT SET statuss=@statuss WHERE ID=@ID", conn);
        //UpCmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int)).Value = lbl.Text;
        //UpCmd.Parameters.Add(new SqlParameter("@statuss", SqlDbType.VarChar)).Value = "Deleted";
        //conn.Open();
        //UpCmd.ExecuteNonQuery();
        //conn.Close();
        //Response.Redirect("default.aspx");
    }

    protected void My_documents_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        DataPager myDocumentsListPage = (My_documents_list.FindControl("My_documents_list_Page")) as DataPager;
        if (myDocumentsListPage != null) myDocumentsListPage.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        SetData(tb_search.Text, status.Text);
    }
    protected void My_users_documents_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        DataPager My_users_documents_list_Page = (My_users_documents_list.FindControl("My_users_documents_list_Page")) as DataPager;
        My_users_documents_list_Page.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        SetData(tb_search.Text, status.Text);
    }
    protected void My_users_share_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        DataPager My_users_share_list_Page = (My_users_share_list.FindControl("My_users_share_list_Page")) as DataPager;
        My_users_share_list_Page.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        share_modal_message.Text = "&nbsp";
        SetDataPopup();
    }

    //protected override void OnPreRender(EventArgs e)
    //{
    //    //if (status.Text == "")
    //    //{
    //    //    SetData(tb_search.Text, "");
    //    //}
    //    //else if (status.Text != null && tb_search.Text == null )
    //    //{
    //    //    SetData("", status.Text);
    //    //}
    //    //else if (status.Text != null && tb_search.Text != null)
    //    //{
    //    //    
    //    //}
    //    //else
    //    //{
    //    //    SetData("", "");            
    //    //}
    //    SetData(tb_search.Text, status.Text);
    //    base.OnPreRender(e);
    //}

    protected void bt_delete_to_all_Click(object sender, EventArgs e)
    {
        //noteiktajam dokumenta nummuram updeito uz deleted
        if (IDdoc.Text == "")
        {
            Delete();
            foreach (string doc in selected_docNumb)
            {
                SqlCommand UpCmd = new SqlCommand("UPDATE DOCUMENT SET statuss=@statuss WHERE document_number=@document_number", conn);
                UpCmd.Parameters.Add(new SqlParameter("@document_number", SqlDbType.VarChar)).Value = doc.ToString();
                UpCmd.Parameters.Add(new SqlParameter("@statuss", SqlDbType.VarChar)).Value = "Deleted";
                conn.Open();
                UpCmd.ExecuteNonQuery();
                conn.Close();
                SetData(tb_search.Text, status.Text);
            }
        }
    }

    protected void bt_delete_me_Click(object sender, EventArgs e)
    {
        if (IDdoc.Text == "")
        {
            Delete();
            foreach (string doc in selected_docNumb)
            {
                SqlCommand UpCmd = new SqlCommand("UPDATE DOCUMENT SET statuss=@statuss WHERE document_number=@document_number AND id_issued_by_user=@id_issued_by_user ", conn);
                UpCmd.Parameters.Add(new SqlParameter("@document_number", SqlDbType.VarChar)).Value = doc.ToString();
                UpCmd.Parameters.Add(new SqlParameter("@id_issued_by_user", SqlDbType.Int)).Value = User.Identity.Name;
                UpCmd.Parameters.Add(new SqlParameter("@statuss", SqlDbType.VarChar)).Value = "Deleted";
                conn.Open();
                UpCmd.ExecuteNonQuery();
                conn.Close();
                SetData(tb_search.Text, status.Text);
            }
        }
        else
        {
            SqlCommand UpCmd = new SqlCommand("UPDATE DOCUMENT SET statuss=@statuss WHERE id=@id", conn);
            UpCmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = Convert.ToInt32(IDdoc.Text);
            UpCmd.Parameters.Add(new SqlParameter("@statuss", SqlDbType.VarChar)).Value = "Deleted";
            conn.Open();
            UpCmd.ExecuteNonQuery();
            conn.Close();
            SetData(tb_search.Text, status.Text);
        }
        Modal_Popup_Delete.Hide();
    }
    protected void bt_delete_cancel_Click(object sender, EventArgs e)
    {
        Modal_PopupShare.Hide();
        SetData(tb_search.Text, status.Text);
    }

    //Search panel
    protected void bt_active_Click(object sender, EventArgs e)
    {
        status.Text = "Active";
        tb_search.Text = "";
        SetData("", status.Text);        
    }
    protected void bt_deleted_Click(object sender, EventArgs e)
    {        
        status.Text = "Deleted";
        tb_search.Text = "";
        SetData("", status.Text);
    }
    protected void bt_all_Click(object sender, EventArgs e)
    {        
        status.Text = "";
        tb_search.Text = "";
        SetData("", status.Text);
    }
    protected void bt_Search_Click(object sender, EventArgs e)
    {
        status.Text = "";
        SetData(tb_search.Text, "");
    }

    protected void bt_add_new_document_Click(object sender, EventArgs e)
    {
        //SetPopupData();
        AddDocument(User.Identity.Name);
        Modal_add_document.Show();
    }

    //Dokumenta Pievienošana/Labošana POPUP
    public void SetPopupData()
    {
        Drop_doc_type.Items.Clear();
        Drop_company_from.Items.Clear();
        Drop_address_company_from.Items.Clear();
        Drop_BANK_company_from.Items.Clear();
        Drop_ACCOUNT_company_from.Items.Clear();

        Drop_client_to.Items.Clear();
        Drop_address_client_to.Items.Clear();
        Drop_BANK_client_to.Items.Clear();
        Drop_ACCOUNT_client_to.Items.Clear();

        FillDDL.Fill_Document_Type(Drop_doc_type);

        FillDDL.Select_company(Drop_company_from, User.Identity.Name, "False");
        Drop_address_company_from.Items.Insert(0, "--Select--");
        Drop_BANK_company_from.Items.Insert(0, "--Select--");
        Drop_ACCOUNT_company_from.Items.Insert(0, "--Select--");
        
        FillDDL.Select_company(Drop_client_to, User.Identity.Name, "True");
        Drop_address_client_to.Items.Insert(0, "--Select--");
        Drop_BANK_client_to.Items.Insert(0, "--Select--");
        Drop_ACCOUNT_client_to.Items.Insert(0, "--Select--");

        FillDDL.Fill_Payment_Type(Drop_pay_type);
        //SetDataArticle();
    }

    public void AddDocument(string id_user)
    {
        //tab_document_articles.Visible = false;
        lit_add_document.Text = "Add new document!";
        lbl_document_id.Text = "";
        lbl_document_edit.Text = "";
        modal_message_document.Text = "&nbsp";
        modal_message_article.Text = "&nbsp";

        if (lbl_document_id.Text == "")
        {
            SetPopupData();
            lbl_user_id.Text = id_user;
            //lbl_user.Text = _User.EditUser(User.Identity.Name)._Name + " " + _User.EditUser(User.Identity.Name)._SecondName;
            Drop_doc_type.SelectedIndex = -1;
            tb_doc_number.Text = "";
            tb_doc_number_OLD.Text = "";
            tb_doc_date.Text = "";
            tb_doc_pay_date.Text = "";

            Drop_company_from.SelectedIndex = -1;
            Drop_address_company_from.SelectedIndex = -1;
            Drop_BANK_company_from.SelectedIndex = -1;
            Drop_ACCOUNT_company_from.SelectedIndex = -1;

            Drop_client_to.SelectedIndex = -1;
            Drop_address_client_to.SelectedIndex = -1;
            Drop_BANK_client_to.SelectedIndex = -1;
            Drop_ACCOUNT_client_to.SelectedIndex = -1;

            Drop_pay_type.SelectedIndex = -1;
            tb_delivery_place.Text = "";

            tab_document_articles.Enabled = false;
        }
    }
    public void EditDocument(string id_user, string id_document)
    {
        SetPopupData();
        //tab_document_articles.Visible = true;
        modal_message_document.Text = "&nbsp";
        modal_message_article.Text = "&nbsp";
        lit_add_document.Text = "Edit document!";
        tab_document_articles.Enabled = true;

        lbl_document_edit.Text = "Edit";
        lbl_user_id.Text = id_user;
        lbl_document_id.Text = id_document;

        //lbl_user.Text = _User.EditUser(User.Identity.Name)._Name + " " + _User.EditUser(User.Identity.Name)._SecondName;

        Drop_doc_type.SelectedValue = _Invoice.EditDocument(id_document).id_document_type.ToString();
        tb_doc_number.Text = _Invoice.EditDocument(id_document).document_number.ToString();
        tb_doc_date.Text = _Invoice.EditDocument(id_document).document_date.ToString("yyyy.MM.dd");
        tb_doc_pay_date.Text = _Invoice.EditDocument(id_document).document_payment_date.ToString("yyyy.MM.dd");

        Drop_company_from.SelectedValue = _Invoice.EditDocument(id_document).id_company_issued_by.ToString();

        FillDDL.Select_addresses(Drop_address_company_from, Drop_company_from.SelectedValue.ToString());

        Drop_address_company_from.SelectedValue = _Invoice.EditDocument(id_document).id_address_company_by.ToString();
        FillDDL.Select_banks(Drop_BANK_company_from, Drop_company_from.SelectedValue.ToString());
        Drop_BANK_company_from.SelectedValue = _Invoice.EditDocument(id_document).id_bank_company_by.ToString();
        FillDDL.Select_bank_accounts(Drop_ACCOUNT_company_from, Drop_company_from.SelectedValue.ToString(), Drop_BANK_company_from.SelectedValue.ToString());
        Drop_ACCOUNT_company_from.SelectedValue = _Invoice.EditDocument(id_document).id_account_company_by.ToString();

        Drop_client_to.SelectedValue = _Invoice.EditDocument(id_document).id_client_issued_to.ToString();
        FillDDL.Select_addresses(Drop_address_client_to, Drop_client_to.SelectedValue.ToString());
        Drop_address_client_to.SelectedValue = _Invoice.EditDocument(id_document).id_address_client_to.ToString();
        FillDDL.Select_banks(Drop_BANK_client_to, Drop_client_to.SelectedValue.ToString());
        Drop_BANK_client_to.SelectedValue = _Invoice.EditDocument(id_document).id_bank_client_to.ToString();
        FillDDL.Select_bank_accounts(Drop_ACCOUNT_client_to, Drop_client_to.SelectedValue.ToString(), Drop_BANK_client_to.SelectedValue.ToString());
        Drop_ACCOUNT_client_to.SelectedValue = _Invoice.EditDocument(id_document).id_account_client_to.ToString();

        Drop_pay_type.SelectedValue = _Invoice.EditDocument(id_document).id_payment_type.ToString();
        tb_delivery_place.Text = _Invoice.EditDocument(id_document).place_of_delivery.ToString();        
        SetDataArticle();
        //Modal_add_document.Show();
    }

    //Izvēloties dokumenta tipu tiek ģenerēts numurs skatoties uz DB esošiem numuriem
    public void GenerateNumber()
    {
        string doc;
        string doc_type = Drop_doc_type.SelectedItem.ToString();
        if (doc_type == "Priekšapmaksas rēķins")
        {
            doc = doc_type.Substring(0, 2);
        }
        else
        {
            doc = doc_type.Substring(0, 1);
        }

        List<int> number = new List<int>();
        List<string> DocNum = new List<string>();
        _Invoice.DocNumber(Drop_doc_type.SelectedValue.ToString(), doc, DocNum);

        foreach (string doc_num in DocNum)
        {
            if (doc_num.StartsWith("PR"))
            {
                string num = doc_num.Substring(2, doc_num.Length - 7);
                number.Add(Convert.ToInt32(num));
            }
            else
            {
                string num = doc_num.Substring(1, doc_num.Length - 6);
                number.Add(Convert.ToInt32(num));
            }
        }

        DateTime dt = DateTime.Now;
        string year = dt.Year.ToString();
        if (number.Count == 0)
        {
            number.Add(1);
            int maximum = number.Max();
            if (doc_type == "Priekšapmaksas rēķins")
            {
                doc = doc_type.Substring(0, 2);
                string date = year;
                tb_doc_number.Text = doc.ToUpper() + maximum + "/" + date;
            }
            else
            {
                doc = doc_type.Substring(0, 1);
                string date = year;
                tb_doc_number.Text = doc.ToUpper() + maximum + "/" + date;
            }
            number.Clear();
        }
        else
        {
            int maximum = number.Max();
            if (doc_type == "Priekšapmaksas rēķins")
            {
                doc = doc_type.Substring(0, 2);
                string date = year;
                maximum++;
                tb_doc_number.Text = doc.ToUpper() + maximum + "/" + date;
            }
            else
            {
                doc = doc_type.Substring(0, 1);
                string date = year;
                maximum++;
                tb_doc_number.Text = doc.ToUpper() + maximum + "/" + date;
            }
        }

    }
    protected void Drop_doc_type_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Drop_doc_type.SelectedItem.ToString() != "--Select--")
        {
            //Ja ir Edit un nomaina doc nr. tad esošo nr. ieliek blakus tb. un ja uzliek atpakaļ tad paliek esošais nr. citādi, tiek ģenērēts jauns nr
            if (lbl_document_edit.Text == "Edit")
            {
                int doc_type_id = _Invoice.EditDocument(lbl_document_id.Text).id_document_type;
                if (doc_type_id != Convert.ToInt32(Drop_doc_type.SelectedValue))
                {
                    tb_doc_number_OLD.Text = "Old: " + _Invoice.EditDocument(lbl_document_id.Text).document_number;
                    GenerateNumber();
                }
                else
                {
                    tb_doc_number.Text = _Invoice.EditDocument(lbl_document_id.Text).document_number;
                    tb_doc_number_OLD.Text = "";
                }
            }
            else
            {
                GenerateNumber();
            }
        }
        else
        {
            tb_doc_number.Text = "";
        }
    }

    protected void Drop_company_from_SelectedIndexChanged(object sender, EventArgs e)
    {
        Drop_address_company_from.Items.Clear();
        Drop_BANK_company_from.Items.Clear();
        Drop_ACCOUNT_company_from.Items.Clear();
        Drop_ACCOUNT_company_from.Items.Insert(0, "--Select--");

        FillDDL.Select_addresses(Drop_address_company_from, Drop_company_from.SelectedValue.ToString());
        FillDDL.Select_banks(Drop_BANK_company_from, Drop_company_from.SelectedValue.ToString());
    }
    protected void Drop_company_from_bank_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDDL.Select_bank_accounts(Drop_ACCOUNT_company_from, Drop_company_from.SelectedValue.ToString(), Drop_BANK_company_from.SelectedValue.ToString());
    }

    protected void Drop_client_to_SelectedIndexChanged(object sender, EventArgs e)
    {
        Drop_address_client_to.Items.Clear();
        Drop_BANK_client_to.Items.Clear();
        Drop_ACCOUNT_client_to.Items.Clear();
        Drop_ACCOUNT_client_to.Items.Insert(0, "--Select--");

        FillDDL.Select_addresses(Drop_address_client_to, Drop_client_to.SelectedValue.ToString());
        FillDDL.Select_banks(Drop_BANK_client_to, Drop_client_to.SelectedValue.ToString());
    }
    protected void Drop_client_to_bank_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDDL.Select_bank_accounts(Drop_ACCOUNT_client_to, Drop_client_to.SelectedValue.ToString(), Drop_BANK_client_to.SelectedValue.ToString());
    }

    //POPUP poga
    protected void bt_add_document_Click(object sender, EventArgs e)
    {
        string id = lbl_document_id.Text;
        string doc_numb = tb_doc_number.Text;
        string doc_date = tb_doc_date.Text;
        string doc_pay_date = tb_doc_pay_date.Text;
        string id_isu_user = User.Identity.Name;
        string id_company_by = Drop_company_from.SelectedItem.Value;
        string id_client_to = Drop_client_to.SelectedItem.Value;
        string id_document_type = Drop_doc_type.SelectedItem.Value;
        string id_payment_type = Drop_pay_type.SelectedItem.Value;
        string delivery_place = tb_delivery_place.Text;
        string address_company_by = Drop_address_company_from.SelectedItem.Value;
        string address_client_to = Drop_address_client_to.SelectedItem.Value;
        string bank_company_by = Drop_BANK_company_from.SelectedItem.Value;
        string bank_client_to = Drop_BANK_client_to.SelectedItem.Value;
        string account_company_by = Drop_ACCOUNT_company_from.SelectedItem.Value;
        string account_client_to = Drop_ACCOUNT_client_to.SelectedItem.Value;
        string statuss = "Active";

        if (lbl_document_edit.Text == "Edit")
        {
            try
            {
                _Invoice.Update(id, doc_numb, doc_date, doc_pay_date, id_isu_user, id_company_by, id_client_to,
                    id_document_type, id_payment_type, delivery_place, address_company_by, address_client_to,
                    bank_company_by, bank_client_to, account_company_by, account_client_to, statuss);
                if (modal_message_document.ForeColor != System.Drawing.Color.Green)
                {
                    modal_message_document.Text = "Saved!";
                    modal_message_document.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_document.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_document.Text = "Error updatinsg data!";
                    modal_message_document.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        else
        {
            try
            {
                _Invoice.Insert(doc_numb, doc_date, doc_pay_date, id_isu_user, id_company_by, id_client_to,
                     id_document_type, id_payment_type, delivery_place, address_company_by, address_client_to,
                     bank_company_by, bank_client_to, account_company_by, account_client_to, statuss);

                SqlCommand sCmd_MAX_document_id = new SqlCommand("SELECT MAX(id) FROM document WHERE id_issued_by_user=@issued_by_user_id", conn);
                sCmd_MAX_document_id.Parameters.Add(new SqlParameter("@issued_by_user_id", SqlDbType.Int)).Value = lbl_user_id.Text;
                conn.Open();
                lbl_document_id.Text = Convert.ToString(sCmd_MAX_document_id.ExecuteScalar());
                conn.Close();

                EditDocument(lbl_user_id.Text, lbl_document_id.Text);

                if (modal_message_document.ForeColor != System.Drawing.Color.Green)
                {
                    modal_message_document.Text = "Saved!";
                    modal_message_document.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch
            {
                if (modal_message_document.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_document.Text = "Error saving data!";
                    modal_message_document.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
    }
    protected void bt_add_document_cancel_Click(object sender, EventArgs e)
    {
        Modal_add_document.Hide();
    }

    //Article TAB    
    private void SetDataArticle()
    {
        if (lbl_document_id.Text != "")
        {
            List<_Article> Document_articles = _Article.SlectArticle(lbl_document_id.Text);
            article_list.DataSource = Document_articles;
            article_list.DataBind();
            Modal_add_document.Show();
        }        
    }

    protected void article_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Insert_article")
        {            
            var art_name = e.Item.FindControl("tb_name_insert") as TextBox;
            var art_count = e.Item.FindControl("tb_count_insert") as TextBox;
            var art_price = e.Item.FindControl("tb_price_insert") as TextBox;

            _Article.Insert(lbl_document_id.Text, art_name.Text, art_count.Text, art_price.Text);
            SetDataArticle();
        }
        if (e.CommandName == "Update_article")
        {
            var article_ID = e.Item.FindControl("id_articleLabel") as Label;
            var document_ID = e.Item.FindControl("id_documentLabel") as Label;
            var art_name = e.Item.FindControl("tb_name") as TextBox;
            var art_count = e.Item.FindControl("tb_count") as TextBox;
            var art_price = e.Item.FindControl("tb_price") as TextBox;

            _Article.Update(article_ID.Text, document_ID.Text, art_name.Text, art_count.Text, art_price.Text);
            article_list.EditIndex = -1;
            SetDataArticle();
        }
        if (e.CommandName == "Cancel_article")
        {

        }
        if (e.CommandName == "Delete")
        {
            var article_ID = e.Item.FindControl("id_articleLabel") as Label;
            int ID = Convert.ToInt32(article_ID.Text);
            _Article.Delete(ID);
        }
    }
    protected void article_list_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        article_list.EditIndex = e.NewEditIndex;
        SetDataArticle();
    }    
    protected void article_list_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        //Slēpjam nevajadzīgās article kolonnas
        e.Item.FindControl("article_ID").Visible = false;
        e.Item.FindControl("document_ID").Visible = false;
    }
}



